// Model of the blackjack table
// doesnt know about the rules of the game, but knows the basic changes it can make to its state
// things like making a bet, dealing a card

package sbcc.edu.blackjack;

import java.util.ArrayList;

public class Table {
	private int id;

	// MAX_ID is the maximum number of tables that can be created
	// idsInUse is the list consisting of the ids representing tables created
	// Each time a table is created, it's id gets put in idsInUse
	// When a table is closed, it's id is removed, so it is available
	private static final int MAX_ID = 5;
	private static ArrayList<Integer> idsInUse;

	public final int MAX_PLAYERS = 5;
	private final int NO_TABLE = 0;

	private Player[] players;
	Shoe shoe;

	public Table() {
		players = new Player[MAX_PLAYERS];
		idsInUse = new ArrayList<Integer>();
		this.setId(getAvailableId());
		shoe = new Shoe();
	}

	/*
	 * getAvailableId will return the next id number not currently in use if
	 * none are available, it returns zero
	 */
	private int getAvailableId() {
		int newId = 0;
		for (int i = 1; i <= MAX_ID; i++) {
			if (idsInUse.indexOf(i) < 0) {
				newId = i;
				idsInUse.add(i);
				break;
			}
		}
		return newId;
	}

	private void setIdAvailable() {
		idsInUse.remove(id);
	}

	public void dealCardTo(Player player) {
		player.addCard(shoe.drawCard());
	}

	public boolean hasPlayers() {
		boolean result = false;
		for (Player p : players) {
			if (p != null)
				result = true;
		}
		return result;
	}

	public int numPlayers() {
		int result = 0;
		for (Player p : players) {
			if (p != null) {
				result += 1;
			}
		}
		return result;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return id;
	}

	public void addPlayer(Player player) {
		player.setTableId(id);
		for (int i = 0; i < players.length; i++) {
			if (players[i] == null) {
				players[i] = player;
				break;
			}
		}
	}

	public void removePlayer(Player player) {
		boolean playersLeft = false;
		for (int i = 0; i < players.length; i++) {
			if (players[i] == player) {
				players[i] = null;
			} else {
				if (players[i] != null) {
					playersLeft = true;
				}
			}
		}
		player.setTableId(NO_TABLE);
		if (!playersLeft) {
			setIdAvailable();
			// TODO should release all resources associated with this table
		}
	}

	public Player[] getAllPlayers() {
		return players;
	}

	public Shoe getShoe() {
		return shoe;
	}
}
